package com.zzx.graduation.service;


import com.zzx.graduation.entity.GroupChat;
import com.zzx.graduation.entity.User;
import com.zzx.graduation.repository.GroupRepository;
import com.zzx.graduation.repository.NewsRepository;
import com.zzx.graduation.repository.UserRepository;
import com.zzx.graduation.utils.StringUtils;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;


@Component
public class GroupChatService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private GroupRepository groupRepository;
    @Autowired
    private NewsRepository newsRepository;

    /**
     * 查询一个人所有群
     * @param id 用户id
     * @return
     */
    public List<GroupChat> findGroups(Integer id){
        User user = userRepository.findById(id).get();
        Set<GroupChat> groupSet = user.getGroupSet();
        return new ArrayList<GroupChat>(groupSet);
    }

    /**
     * 查询一个群的具体信息
     * @param id  群聊id
     * @return
     */
    public  HashMap<GroupChat, Set<User>> findOneGroup(Integer id) {
        GroupChat groupChat = groupRepository.findById(id).get();
        Set<User> userSet = groupChat.getUserSet();
        HashMap<GroupChat, Set<User>> groupChatSetHashMap = new HashMap<>();
        groupChatSetHashMap.put(groupChat, userSet);
        return groupChatSetHashMap;
    }

    public GroupChat addGroup(GroupChat groupChat, Integer[] ids) {
        if (ids != null) {
            String userStr = StringUtils.arraryToString(ids);
            groupChat.setUserStr(userStr);
            List<User> allById = userRepository.findAllById(Arrays.asList(ids));
            for (User user : allById) {
                user.getGroupSet().add(groupChat);
            }

            groupChat.getUserSet().addAll(new HashSet<>(allById));
          //  userRepository.saveAll(allById);
            GroupChat save = groupRepository.save(groupChat);
            return save;
        }else {
            return null;
        }
    }


    public GroupChat modify(GroupChat groupChat, Integer[] ids) {

        return addGroup(groupChat, ids);
    }

    public boolean deleteGroup(Integer id) {
        try {
            GroupChat groupChat = groupRepository.findById(id).get();
            Set<User> userSet = groupChat.getUserSet();
            for (User user : userSet) {
              if (  user.getGroupSet().contains(groupChat)){
                  user.getGroupSet().remove(groupChat);
              }
            }
           // groupChat.getUserSet().clear();
            //groupRepository.save(groupChat);
            groupRepository.deleteById(id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
